﻿using HCMS.CommonDtos;
using HCMS.Entities.Base;
using HCMS.Enum;
using HCMS.Extensions;
using HCMS.IServices.Base;
using HCMS.Web.Manage.Filter;
using HCMS.Web.Manage.Models;
using Microsoft.AspNetCore.Mvc;
using System.Text;

namespace HCMS.Web.Manage.Controllers.Module.Base
{
    /// <summary>
    /// 行政区划
    /// </summary>
    public class SystemAreaController : ModuleController
    {
        private readonly ISystemAreaAppService systemAreaAppService;

        public SystemAreaController(
            ISystemAreaAppService systemAreaAppService
            )
        {
            this.systemAreaAppService = systemAreaAppService;
        }

        #region 列表
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult List()
        {
            return View($"{BasePath}/Base/SystemArea/List.cshtml");
        }

        /// <summary>
        /// 列表 Ajax
        /// </summary>
        /// <returns></returns>
        [ActionName("List")]
        [HttpPost]
        public async Task<IActionResult> PostList()
        {
            var searchArgs = new SearchArgsDto()
            {
                SearchRange = Request.Form["searchRange"].ToInt(9999),

                Status = Request.Form["status"].ToInt(9999),

                SearchName = Request.Form["searchName"].ToString(""),
                SearchKey = Request.Form["searchKey"].ToString(""),

                ParentId = Request.Form["parentId"].ToInt(0)
            };

            var pager = new PagerArgsDto()
            {
                CurrentPageIndex = Request.Form["page"].ToInt(1),
                PageSize = Request.Form["limit"].ToInt(10)
            };

            var result = await systemAreaAppService.ManageList(searchArgs, pager);

            return Json(new { code = 0, data = result.Data, count = result.PagerInfo.RowCount, msg = "ok" });
        }
        #endregion

        #region 新增、编辑、保存
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            var model = new SystemArea();
            return View($"{BasePath}/Base/SystemArea/Edit.cshtml", model);
        }

        /// <summary>
        /// 添加子级
        /// </summary>
        /// <param name="parentId">父级 Id</param>
        /// <returns></returns>
        public IActionResult AddChildren(int parentId = 0)
        {
            var model = new SystemArea()
            {
                ParentId = parentId
            };
            return View($"{BasePath}/Base/SystemArea/Edit.cshtml", model);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Edit(int id)
        {
            if (id <= 0)
            {
                return Content("参数无效");
            }

            var model = await systemAreaAppService.BaseFirstOrDefaultAsync(t => t.Id == id);
            if (model == null)
            {
                return Content($"没有找到【id：{id}】区域信息");
            }

            return View($"{BasePath}/Base/SystemArea/Edit.cshtml", model);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="systemArea"></param>
        /// <returns></returns>
        public async Task<IActionResult> Save(SystemArea systemArea)
        {
            SystemArea? result = null;

            if (systemArea == null)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "参数异常" });
            }
            if (string.IsNullOrWhiteSpace(systemArea.Name))
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请填写名称" });
            }

            var parentId = Request.Form["ParentId"].ToInt(-1);
            if (parentId == -1)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请选择所属上级" });
            }

            var parentPath = (await systemAreaAppService.BaseFirstOrDefaultAsync(t => t.Id == parentId))?.ParentPath;

            if (!string.IsNullOrWhiteSpace(parentPath))
            {
                var pathIdArray = parentPath.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var pathIdList = Array.ConvertAll(pathIdArray, int.Parse).ToList();
                pathIdList.Add(parentId);
                parentPath = string.Join(",", pathIdList);
            }
            else
            {
                parentPath = $"{parentId}";
            }

            var entity = await systemAreaAppService.BaseFirstOrDefaultAsync(t => t.Id == systemArea.Id);
            if (entity != null)
            {
                if (entity.Id == parentId)
                {
                    throw new Exception("不能选择自己作为上级，请重新选择");
                }

                await TryUpdateModelAsync(entity);
                entity.ParentId = parentId;
                entity.ParentPath = parentPath;
                entity.UpdateTime = DateTime.Now;
                entity.UpdateUser = CurrentAdmin.AdminName;
                result = await systemAreaAppService.BaseUpdateAsync(entity);
            }
            else
            {
                entity = new SystemArea();
                await TryUpdateModelAsync(entity);
                entity.ParentId = parentId;
                entity.ParentPath = parentPath;
                entity.CreateTime = DateTime.Now;
                entity.CreateUser = CurrentAdmin.AdminName;
                entity.UpdateTime = DateTime.Now;
                entity.UpdateUser = CurrentAdmin.AdminName;

                result = await systemAreaAppService.BaseInsertAsync(entity);
            }

            if (result != null)
            {
                return Json(new AjaxResultDto() { Message = "处理成功" });
            }
            else
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "处理失败" });
            }
        }
        #endregion

        #region 获取区域树结构
        /// <summary>
        /// 获取区域树结构
        /// </summary>
        /// <returns></returns>
        [DefaultPermission]
        [HttpGet]
        public async Task<IActionResult> AllTree()
        {
            var result = await systemAreaAppService.GetAllTree();
            return Json(result);
        }
        #endregion

        #region 抓取数据
        /// <summary>
        /// 抓取数据
        /// </summary>
        /// <returns></returns>
        public IActionResult CrawlData()
        {
            return View($"{BasePath}/Base/SystemArea/CrawlData.cshtml");
        }

        /// <summary>
        /// 解析 Html
        /// </summary>
        /// <returns></returns>
        [DefaultPermission]
        [HttpPost]
        public async Task<IActionResult> AnalysisHtml()
        {
            var webUrl = Request.Form["webUrl"].ToString("");
            if (string.IsNullOrWhiteSpace(webUrl))
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请填写网站地址" });
            }

            var htmlContent = "";
            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetAsync(webUrl);
                response.EnsureSuccessStatusCode();

                /*
                    默认的 .NET Core 框架不包含 GBK 编码，不包含
                    除了代码页为 28591 和 Unicode(utf-8,utf-16) 之外的其他编码，
                    需要安装 System.Text.Encoding.CodePages 才能使用
                 */
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

                htmlContent = await response.Content.ReadAsStringAsync();
            }

            return Json(new AjaxResultDto() { Result = htmlContent });
        }

        /// <summary>
        /// 保存 抓取数据
        /// </summary>
        /// <returns></returns>
        [ActionName("CrawlData")]
        [HttpPost]
        // 允许提交的表单条目的数量限制，超过该限制的表单无法提交。默认：1024
        // 由于行政区划数据庞大，需要对此限制进行调整
        [RequestFormLimits(ValueCountLimit = int.MaxValue)]
        public async Task<IActionResult> PostCrawlData(CrawlAreaDataModel data)
        {
            if (data == null)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "参数异常，请稍后再试" });
            }

            if (data.AreaData == null || data.AreaData.Count == 0)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请先选中要抓取数据的省份" });
            }

            foreach (var provinceItem in data.AreaData)
            {
                // 删除旧数据
                var province = await systemAreaAppService.BaseFirstOrDefaultAsync(t => t.Name == provinceItem.ProvinceName);
                if (province != null)
                {
                    await systemAreaAppService.DelByProvinceId(province.Id);
                }

                // 新增省份数据
                var regionalismCodeDic = new Dictionary<string, int>() {
                                { "北京市", 110000 },
                                { "天津市", 120000 },
                                { "河北省", 130000},
                                { "山西省", 140000 },
                                { "内蒙古自治区", 150000 },
                                { "辽宁省", 210000 },
                                { "吉林省", 220000 },
                                { "黑龙江省", 230000 },
                                { "上海市", 310000 },
                                { "江苏省", 320000  },
                                { "浙江省", 330000 },
                                { "安徽省", 340000 },
                                { "福建省", 350000 },
                                { "江西省", 360000  },
                                { "山东省", 370000  },
                                { "河南省", 410000  },
                                { "湖北省", 420000  },
                                { "湖南省", 430000 },
                                { "广东省", 440000  },
                                { "广西壮族自治区", 450000  },
                                { "海南省", 460000 },
                                { "重庆市", 500000 },
                                { "四川省", 510000 },
                                { "贵州省", 520000 },
                                { "云南省", 530000  },
                                { "西藏自治区", 540000 },
                                { "陕西省", 610000 },
                                { "甘肃省", 620000  },
                                { "青海省", 630000  },
                                { "宁夏回族自治区", 640000  },
                                { "新疆维吾尔自治区", 650000 },
                                { "香港特别行政区", 810000 },
                                { "澳门特别行政区", 820000 },
                                { "台湾省", 710000 }
                };

                var provinceId = 0;
                province = new SystemArea()
                {
                    CreateTime = DateTime.Now,
                    CreateUser = "系统",
                    UpdateTime = DateTime.Now,
                    UpdateUser = "系统",
                    Name = provinceItem.ProvinceName,
                    AreaType = (int)SystemAreaType.Province,
                    RegionalismCode = regionalismCodeDic[provinceItem.ProvinceName],
                    PostCode = 0,
                    AreaCode = "0",
                    ParentPath = "0",
                    ParentId = 0,
                };
                var provinceResult = await systemAreaAppService.BaseInsertAsync(province);
                if (provinceResult != null)
                {
                    provinceId = provinceResult.Id;
                }

                // 新增城市数据
                foreach (var cityItem in provinceItem.CityList)
                {
                    var city = new SystemArea()
                    {
                        CreateTime = DateTime.Now,
                        CreateUser = "系统",
                        UpdateTime = DateTime.Now,
                        UpdateUser = "系统",
                        Name = cityItem.CityName,
                        AreaType = (int)SystemAreaType.City,
                        RegionalismCode = cityItem.RegionalismCode,
                        PostCode = cityItem.PostCode,
                        AreaCode = cityItem.AreaCode.ToString("0"),
                        ParentId = provinceId,
                        ParentPath = $"0,{provinceId}"
                    };

                    var cityResult = await systemAreaAppService.BaseInsertAsync(city);
                    if (cityResult != null)
                    {
                        // 新增区域数据
                        foreach (var areaItem in provinceItem.AreaList)
                        {
                            if (areaItem.CityName != city.Name) { continue; }

                            var area = new SystemArea()
                            {
                                CreateTime = DateTime.Now,
                                CreateUser = "系统",
                                UpdateTime = DateTime.Now,
                                UpdateUser = "系统",
                                Name = areaItem.AreaName,
                                AreaType = (int)SystemAreaType.Area,
                                RegionalismCode = areaItem.RegionalismCode,
                                PostCode = areaItem.PostCode,
                                AreaCode = areaItem.AreaCode.ToString("0"),
                                ParentId = cityResult.Id,
                                ParentPath = $"0,{provinceId},{cityResult.Id}"
                            };

                            await systemAreaAppService.BaseInsertAsync(area);
                        }
                    }
                }
            }

            return Json(new AjaxResultDto() { Message = "处理成功" });
        }
        #endregion
    }
}
